/**
 *@ClassName selfAjax
 *@Description  自定义的Ajax，
 * 页面引用时记得放在jquery-3.4.1.min.js与globalParmas.js的后面
 *@Author JiJiang
 *@Date 2022/8/9 10:30
 *@Version 1.0
 * @return {null}
 */
//引入jquery文件
// import './jquery-3.4.1.min'
// import './globalParmas'


function MyAjax(url = "",
                type = "",
                param = {},
                headers = {},
                contentType = "application/x-www-form-urlencoded;charset=UTF-8",
                async = false,
                selfSuccessCallBack = function (result, textStatus, response) {
                }
) {
    let retData = {
        code: 0,
        msg: "",
        count: 0,
        data: {},
        status: 0
    };
    $.ajax({
        url: url,//请求后端的地址
        type: type,//发送消息的类型
        data: param,//发送给后端的参数
        headers: headers,//请求头
        contentType: contentType,//请求消息类型
        async: async,//取消异步
        dataType: "json",
        beforeSend: function (xhr) {

            //region （舍弃）
            // //尝试从localStorage获取codeKey
            // let codeKey = localStorage.getItem(CHECK_CODE_KEY);
            // //验证码的key如果存在
            // if (codeKey != null) {
            //     //将codeKey存放到请求头
            //     xhr.setRequestHeader(CHECK_CODE_KEY, codeKey);
            // }
            // let token = localStorage.getItem(TOKEN_KEY);
            // if (token != null) {
            //     xhr.setRequestHeader(TOKEN_KEY, token);
            //     // xhr.setRequestHeader(ROLE_KEY,ROLE_ADMIN_VALUE);
            // }
            //endregion


        },
        success: function (result, textStatus, response) {
            //如果是异步请求
            if (async) {
                //调用自定义请求
                selfSuccessCallBack(result, textStatus, response);
                return;
            }

            //region （舍弃）
            // //获取响应头中的codeKey
            // let codeKey = response.getResponseHeader(CHECK_CODE_KEY);
            // //如果响应头中包含codeKey
            // if (codeKey != null) {
            //     //将codeKey存储到localStorage
            //     localStorage.setItem(CHECK_CODE_KEY, codeKey);
            // }
            //endregion

            if (result != null) {
                if ('code' in result) {
                    retData.code = result.code;
                }
                if ('count' in result) {
                    retData.count = result.count;
                }
                if ('msg' in result) {
                    retData.msg = result.msg;
                }
                if ('data' in result) {
                    retData.data = result.data;
                }
            }
            //赋值状态码
            retData.status = response.status;

        }
        , error: function (jqXHR, textStatus, errorThrown) {
            // console.log("jqXHR == ",jqXHR);
            retData.status = jqXHR.status
        }
    });
    return retData;
}

/**
 * 将参数对象拼接到地址栏
 */
function joinParamToUrl(url = "", param = {}) {


    //获取参数对象的所有属性名称的数组
    let paramKeys = Object.keys(param);

    //如果有属性，即有参数对象有值
    if (paramKeys.length > 0) {

        //获取属性数组长度
        let keysLen = paramKeys.length;

        url += "?";
        //用于接收属性名
        let keyName = null;
        //用于接收属性值
        let keyVal = null;
        //遍历属性名数组
        for (let i = 0; i < keysLen; i++) {

            keyName = paramKeys[i];

            keyVal = param[`${keyName}`];

            // console.log("同步ajax 的get请求 key=" + keyName + "value=" + keyVal);

            url += `${keyName}=${keyVal}`
            //如果不是最后一个属性
            if (i < keysLen - 1) {
                url += "&";
            }
        }

    }

    return url;
}


//region 同步请求的封装


//get请求
function getRequest(url = "", param = {}, headers = {}) {
    url = joinParamToUrl(url, param);

    // console.log("同步ajax 的get请求地址为 " + url);

    return MyAjax(url, "GET", undefined, headers, undefined, undefined, undefined);
}


//post请求
function postRequest(url = "", param = {}, headers = {}, paramInBody = false) {
    //如果参数存放在请求体中
    if (paramInBody) {
        //将参数转为json字符串
        param = JSON.stringify(param);
        return MyAjax(url, "POST", param, headers, "application/json", undefined, undefined);
    }

    return MyAjax(url, "POST", param, headers, undefined, undefined, undefined);
}


//put请求
function putRequest(url = "", param = {}, headers = {}, paramInBody = false) {

    //如果参数存放在请求体中
    if (paramInBody) {
        //将参数转为json字符串
        param = JSON.stringify(param);
        return MyAjax(url, "PUT", param, headers, "application/json", undefined, undefined);
    }
    return MyAjax(url, "PUT", param, headers, undefined, undefined, undefined);

}


//delete请求
function deleteRequest(url = "", param = {}, headers = {}) {
    return MyAjax(url, "DELETE", param, headers, undefined, undefined, undefined);
}

//endregion


//region 异步请求的封装


/**
 * 异步的get请求
 * @param url
 * @param param
 * @param headers
 * @param successCallback
 * @returns {*}
 */
function asyncGetRequest(url = "", param = {}, headers = {}, successCallback = (result) => {
}) {

    url = joinParamToUrl(url, param);
    return MyAjax(url, "GET", param, headers, undefined, true, successCallback);

}


/**
 * 异步post请求
 * @param url
 * @param param
 * @param headers
 * @param successCallback
 * @returns {*}
 */
function asyncPostRequest(url = "", param = {}, headers = {}, paramInBody = false, successCallback = () => {
}) {
    //如果参数存放在请求体中
    if (paramInBody) {
        //将参数转为json字符串
        param = JSON.stringify(param);
        return MyAjax(url, "POST", param, headers, "application/json", true, successCallback);
    }
    return MyAjax(url, "POST", param, headers, undefined, true, successCallback);
}

/**
 * 异步put请求
 * @param url
 * @param param
 * @param headers
 * @param paramInBody
 * @param successCallback
 * @returns {*}
 */
function asyncPutRequest(url = "", param = {}, headers = {}, paramInBody = false, successCallback = () => {
}) {

    //如果参数存放在请求体中
    if (paramInBody) {
        //将参数转为json字符串
        param = JSON.stringify(param);
        return MyAjax(url, "PUT", param, headers, "application/json", true, successCallback);
    }
    return MyAjax(url, "PUT", param, headers, undefined, true, successCallback);

}


//delete请求
function asyncDeleteRequest(url = "", param = {}, headers = {},callback = (result)={}) {
    return MyAjax(url, "DELETE", param, headers, undefined, true, callback);
}

//endregion